package cn.bocweb.spinning.view.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.TextUtils;

import java.util.Timer;
import java.util.TimerTask;

import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.LibListBean;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.view.common.BaseActivity;

public class LoadingActivity extends BaseActivity {

    Timer timer;
    boolean isFirst = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading);
        initFirstOpen();
    }

    private void initFirstOpen() {
        SharedPreferences sp = getSharedPreferences(Constant.IS_FIRST_OPEN, Context.MODE_PRIVATE);
        isFirst = sp.getBoolean(Constant.KEY_FIRST_OPEN, true);

        if (isFirst) {
            Editor editor = sp.edit();
            editor.putBoolean(Constant.KEY_FIRST_OPEN, false);
            editor.apply();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        initDelay();
    }

    private void initIntent() {
        Intent intent;
        if (isFirst) {
            intent = new Intent(this, GuideActivity.class);
        } else {
            LibListBean.DataEntity dataEntity = new LibListBean.DataEntity();
            dataEntity.readLibListIntoLocal(this);
            if (TextUtils.isEmpty(dataEntity.getId())) {
                intent = new Intent(this, SetQuesWarehouseActivity.class);
                intent.putExtra(Constant.SET_QUES_WAREHOUSE, Constant.FIRST_OPEN_APP_TO_WAREHOUSE);
            } else {
                intent = new Intent(this, MainActivity.class);
            }
        }
        startActivity(intent);
    }

    private void initDelay() {
        timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {

                initIntent();
                finish();

            }
        };
        timer.schedule(timerTask, 3000);
    }

    @Override
    protected void onStop() {
        super.onStop();
        timer.cancel();
    }
}
